package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	clipboard2 "github.com/atotto/clipboard"
	"golang.design/x/clipboard"
)

func setFontPath() {
	exe1, err := os.Executable()
	if err != nil {
		panic(err)
	}
	path1 := filepath.Dir(exe1)
	fontpath := filepath.Join(path1, "font", "default.ttf")

	err = os.Setenv("FYNE_FONT", fontpath)
	if err != nil {
		panic(err)
	}
}

var text binding.String

func main() {
	setFontPath()
	defer os.Unsetenv("FYNE_FONT")
	text = binding.NewString()

	myApp := app.New()
	myWindow := myApp.NewWindow("AnswerViewer")

	board := widget.NewMultiLineEntry()
	board.Bind(text)
	board.Wrapping = fyne.TextWrapBreak
	board.PlaceHolder = "把关键词复制到剪贴板，此处将显示答案。"

	content := container.NewPadded(board)

	myWindow.SetContent(content)
	//myWindow.SetFixedSize(true)
	myWindow.Resize(fyne.NewSize(480, 320))

	//rpc server
	go queryLoop()

	go func() {
		time.Sleep(time.Second * 3)
		setWindowTopMost("AnswerViewer")
	}()

	myWindow.ShowAndRun()
}

func queryLoop() {
	changed := waitClipboard()

	for s := range changed {
		ret, err := getAnswers(s)
		if err != nil {
			fmt.Println(err.Error())
		}
		showAnswers(ret)
	}

}

func showAnswers(answers []QuestionAnswer) {
	s1 := ""
	for _, v := range answers {
		s1 = s1 + fmt.Sprintf("%v\n%v\n", v.Question, strings.Join(v.Answer, "\n"))
	}
	text.Set(s1)
}

func waitClipboard() chan string {
	ret := make(chan string, 1)

	go func() {
		if runtime.GOOS == "linux" {
			err := clipboard.Init()
			if err != nil {
				panic(err)
			}
			changed := clipboard.Watch(context.Background(), clipboard.FmtText)
			for v := range changed {
				s := string(v)
				ret <- s
			}
		} else if runtime.GOOS == "windows" {
			var lastBuf string
			for {
				buf, _ := clipboard2.ReadAll()

				if strings.Compare(lastBuf, buf) == 0 {
					time.Sleep(time.Millisecond * 500)
				} else {
					lastBuf = buf
					ret <- buf
				}
			}
		}
	}()

	return ret
}
